package com.satan.juc.demo16;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentListExample {

    public static void main(String[] args) throws InterruptedException {
        List<String> list = new CopyOnWriteArrayList<>();
        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        // 添加100个线程，每个线程每隔0.5秒执行一次操作
        for (int i = 0; i < 100; i++) {

            int finalI = i;
            executorService.submit(() -> {
                String action = (finalI % 2 == 0) ? "add" : "remove";
                String item = "item" + (finalI % 5);
                int quantity = 1;

                switch (action) {
                    case "add":
                        list.add(item);
                        break;
                    case "remove":
                        if (list.contains(item)) {
                            list.remove(item);
                        }
                        break;
                    default:
                        break;
                }
            });
        }

        // 等待10分钟后，打印出最终的库存数量
        Thread.sleep(1000);
        System.out.println("Final inventory: " + list);

        // 关闭线程池
        executorService.shutdown();
    }
}
